package com.jr.util;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;

/**
 * 数据库工具类
 */
public class DBHelper {

    //1+2
    public Connection getCon(){
        Connection con=null;
        try {
            //1.手动添加数据库驱动类：
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获得数据库连接对象：x
            String url = "jdbc:mysql://127.0.0.1:3306/jdbc2?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true";
            String username = "root";
            String password = "123456";
             con= DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return con;
    }
    //7
    public void closeAll(Connection con,PreparedStatement ps,ResultSet rs){
      try {
          if (rs != null) {
              rs.close();
          }
          if (ps != null) {
              ps.close();
          }
          if (con != null) {
              con.close();
          }
      } catch (SQLException e) {
          e.printStackTrace();
      }
    }


    //增删改的通用方法
    public int dtUpdate(String sql, Object... obj) {
        Connection con = getCon();
        PreparedStatement ps = null;
        int count = 0;
        try {
            ps = con.prepareStatement(sql);
            for (int i = 0; i < obj.length; i++) {
                Object param = obj[i];
                if (param instanceof String) {
                    // 字符串显式用setString
                    ps.setString(i + 1, (String) param);
                } else {
                    ps.setObject(i + 1, param);
                }
            }
            count = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeAll(con, ps, null);
        }
        return count;
    }

    //通用的查询方法
    public ArrayList dtQuery(String sql, Class cla,Object... obj){
        ArrayList list=new ArrayList();
        Connection con=getCon();
        PreparedStatement ps=null;
        ResultSet rs=null;
        try {
             ps= con.prepareStatement(sql);
            for (int i = 0; i < obj.length; i++) {
                ps.setObject(i + 1, obj[i]);
            }
            rs= ps.executeQuery();
            while (rs.next()) {
                Object o = cla.newInstance();
                Field[] fields = cla.getDeclaredFields();
                for (Field f : fields) {
                    f.setAccessible(true);
                    f.set(o, rs.getObject(f.getName()));
                }
                list.add(o);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            closeAll(con,ps,rs);
        }
        return list;
    }

    public <T> T scalarQuery(String sql, Class<T> clazz, Object... params) {
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            con = getCon();
            if (con == null) {
                throw new SQLException("无法获取数据库连接");
            }

            ps = con.prepareStatement(sql);

            // 设置参数
            if (params != null && params.length > 0) {
                for (int i = 0; i < params.length; i++) {
                    ps.setObject(i + 1, params[i]);
                }
            }

            rs = ps.executeQuery();

            if (rs.next()) {
                Object value = rs.getObject(1);
                if (value == null) {
                    return null;
                }

                if (clazz.isInstance(value)) {
                    return clazz.cast(value);
                }

                if (clazz == Integer.class && value instanceof Long) {
                    return clazz.cast(((Long) value).intValue());
                }
                if (clazz == Long.class && value instanceof Integer) {
                    return clazz.cast(((Integer) value).longValue());
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeAll(con, ps, null);
        }

        return null;
    }

}
